#!/bin/csh
# make_timeprofiles.csh
# Prepare a file containing  time, depth, and the profiles of all available fields 
# from all simulation outputs contained in dirout
# The script must be run before using 2d_timeprofiles.csh
#
# Run it using ./make_timeprofiles.csh
##################################################################################

source simulation.dir

if (! -d $dirout) then
  echo $dirout 'does not exist. Check the path stored in the variable "dirout" '
  exit
endif

set tzfile = time_profiles_{$$}.dat
touch $tzfile

#------------------------------------------------------
# Make a loop over all output files found in dirout
#------------------------------------------------------
if (-e {$dirout}$tzfile) then

  echo {$dirout}$tzfile 'already exisiting'
  echo 'You must delete it before running make_timeprofiles.csh'

else 

  set files = (`ls ${dirout}profiles*.dat`)
  foreach file ($files)
     echo "Current file:" $file

# Extract the current time-step of the simulation
     set nchar = `echo $file | awk '{print length($0)}'`
     set n1 = `echo "scale=1; $nchar - 10" | bc -l`
     set n2 = `echo "scale=1; $nchar - 5" | bc -l`
     set tstep = `echo $file | cut -c ${n1}-${n2}`

# Extract the current time of the simulation from the corresponding grd file
     set grdfile = ${dirout}grd_{$tstep}_.dat
     set ctime = `awk 'NR == 1 {print $5}' $grdfile`

# Extract the number of lines in the profile file (i.e. the number of grid points along z)
     set nline = `awk 'END { print NR }' $file`

# Write into tmp1 a column with the current simulation time
     awk 'BEGIN {for (i = 1; i < '"$nline"'; i++) printf "%s\n", "'"$ctime"'" }' >! tmp1_$$
   
# Write into tmp2 the column of the depth...
     awk 'NR>1 {print $1}' $file >! tmp2_$$

# and in tmp 3,4,5 etc. all fields for which a profile is stored
     awk 'NR>1 {print $2}' $file >! tmp3_$$               # velocity
     awk 'NR>1 {print $3}' $file >! tmp4_$$               # temperature
     awk 'NR>1 {print $4}' $file >! tmp5_$$               # viscosity
     awk 'NR>1 {print $5}' $file >! tmp6_$$               # viscous dissipation
     awk 'NR>1 {print $6}' $file >! tmp7_$$               # composition
     awk 'NR>1 {print $7}' $file >! tmp8_$$               # horizontal velocity
     awk 'NR>1 {print $8}' $file >! tmp9_$$               # vertical velocity
     awk 'NR>1 {print $9}' $file >! tmp10_$$              # heat sources
     awk 'NR>1 {print $10}' $file >! tmp11_$$             # expansivity
     awk 'NR>1 {print $11}' $file >! tmp12_$$             # conductivity
   
# Paste together tmp1, tmp2, ....
     paste tmp1_$$ tmp2_$$ tmp3_$$ tmp4_$$ tmp5_$$ tmp6_$$ tmp7_$$ tmp8_$$ tmp9_$$ tmp10_$$ tmp11_$$ tmp12_$$  >! tmp13_$$

# Append tmp8 to the final file
     cat tmp13_$$ >> $tzfile

     rm -f tmp*

  end

# Move tzfile into the parent simulation directory
  mv $tzfile ${dirout}time_profiles.dat 

endif

